package com.example.threadSimple;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @Author: Ah Nan
 * @Description: 异步线程池调用
 * @Date: 16:24 2020/6/28
 */
public class AsynPaymentService {

    //创建一个线程池，单线程化线程池
    private final ExecutorService single = Executors.newSingleThreadExecutor();

    //创建一个队列
    LinkedBlockingDeque<PaymentModel> taskQueue = new LinkedBlockingDeque<>();

    /**
     实际项目中可以通过注解,当spring容器启动后去启动,
     eg: @PostConstruct  在一个方法里用此注解，会在spring容器加载后，执行这个方法，
     */
    {
        init();
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        AsynPaymentService asynPaymentService = new AsynPaymentService();
        PaymentModel paymentModel = new PaymentModel();
        paymentModel.setCallUrl("www.123456");
        paymentModel.setPaymentAmount(2000);
        asynPaymentService.submitPay(paymentModel);
        long end = System.currentTimeMillis() - start;
        System.out.println("消耗时间为：" + end);
    }

    public void init() {
        single.execute(() -> {
            try {
                //拿到队列中的请求
                PaymentModel paymentModel = taskQueue.take();
                //调用支付方法
                doPay(paymentModel);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    public String submitPay(PaymentModel paymentModel) {
        System.out.println("开始校验支付请求参数");

        //把请求参数加入到队列中
        taskQueue.add(paymentModel);

        //返回支付中
        return "processing";
    }

    public String doPay(PaymentModel paymentModel) {
        System.out.println("开始处理支付请求:" + paymentModel);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "success";
    }
}
